package cn.com.surker.material.service.impl;

import cn.com.surker.base.system.dao.SysStorageDao;
import cn.com.surker.base.system.dao.SysStorageLogDao;
import cn.com.surker.base.system.entity.SysStorageLog;
import cn.com.surker.base.system.vo.SysStorageVo;
import cn.com.surker.common.MessageCenterException;
import cn.com.surker.database.JDBCTemplateCache;
import cn.com.surker.enums.system.DataBaseEnum;
import cn.com.surker.material.entity.MainMaterialInventoryDetail;
import cn.com.surker.material.dao.MainMaterialInventoryDetailDao;
import cn.com.surker.material.service.MaterialInventoryDetailBaseService;
import cn.com.surker.material.vo.MaterialInventoryDetailVo;
import cn.com.surker.system.dao.DataSourceInfoDao;
import cn.com.surker.system.entity.DataSourceInfo;
import cn.com.surker.util.DateUtil;
import cn.com.surker.util.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.jdbc.core.JdbcTemplate;
import cn.com.surker.spring.RestResultDto;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* <p>
    * 材料盘存表 服务实现类
    * </p>
*
* @author admin
* @since 2024-12-05
*/
public abstract class MaterialInventoryDetailBaseServiceImpl extends ServiceImpl<MainMaterialInventoryDetailDao, MainMaterialInventoryDetail> implements MaterialInventoryDetailBaseService {

    @Resource
    protected MainMaterialInventoryDetailDao materialInventoryDetailDao;
    @Resource
    protected DataSourceInfoDao dsDao;
    @Resource
    protected SysStorageDao storageDao;
    @Resource
    protected SysStorageLogDao storageLogDao;

    /**
     * 云端分页查询
     * @param orgId
     * @param today
     * @param materialId
     * @param storageId
     * @param storeType
     * @param searchVal
     * @param startTime
     * @param endTime
     * @return
     */
    public IPage findCloudPage(Long orgId, String today, Long materialId, Long storageId, Integer storeType, String searchVal,
                               Long lineId, Integer isEnjoy,String startTime, String endTime, Integer offset, Integer limit) {
        if (StringUtils.isNull(orgId))
            return null;
        DataSourceInfo ds = dsDao.queryDSByOriginIdV1(orgId, DataBaseEnum.MYSQL.getCode());
        if (ds == null || ds.getStatus() == 1 || ds.getType() != 0)
            return null;
        PageHelper.offsetPage(offset, limit);
        IPage<MaterialInventoryDetailVo> iPage = materialInventoryDetailDao.findCloudPage(new Page<>((offset + limit) /limit, limit),
                ds.getCode(), orgId, today, materialId, storageId, storeType, searchVal, lineId, isEnjoy, startTime, endTime);

        if (!StringUtils.isNull(iPage.getRecords())) {
            PageInfo pageInfo = new PageInfo(iPage.getRecords());
            if (!StringUtils.isNull(pageInfo.getTotal()))
                iPage.setTotal(pageInfo.getTotal());
        }
        return iPage;
    }

    /**
     * 新增盘存明细
     * @param detail
     * @return
     */
    public RestResultDto saveDetail(MainMaterialInventoryDetail detail) {
        if (detail == null)
            throw new MessageCenterException("参数错误");
        DataSourceInfo ds = dsDao.queryDSByOriginIdV1(detail.getOrgId(), DataBaseEnum.MYSQL.getCode());
        if (ds == null || ds.getStatus() == 1 || ds.getType() != 0)
            throw new MessageCenterException("数据源参数错误");
        Date nowDate = new Date();
        detail.setCreateTime(nowDate);
        MainMaterialInventoryDetail oldDetail = materialInventoryDetailDao.findOrgByStorage(ds.getCode(), detail.getOrgId(),
                detail.getToday(), detail.getMaterialId(), detail.getStorageId());
        if (oldDetail != null)
            throw new MessageCenterException(oldDetail.getToday() + "相同仓位、材料已存在盘存明细数据");
        Integer checkTotal = materialInventoryDetailDao.findCheckTotal(ds.getCode(), detail.getOrgId(), detail.getToday(), 1, null);
        if (checkTotal > 0)
            throw new MessageCenterException(detail.getToday() + "盘存明细表已审核,不提供新增操作");
        checkTotal = materialInventoryDetailDao.findCheckTotal(ds.getCode(), detail.getOrgId(), detail.getToday(), null, 1);
        if (checkTotal > 0)
            throw new MessageCenterException(detail.getToday() + "盘存明细表已审核,不提供新增操作");
        if (StringUtils.isNull(detail.getIsCloud()) || detail.getIsCloud() == 1) {//本地数据直接新增
            Integer code = materialInventoryDetailDao.insert(detail);
            if (code > 0)
                return RestResultDto.success("新增成功");
        } else {
            String createTime_ = DateUtil.convertString(nowDate);
            String creator = StringUtils.convertString(detail.getCreator());
            String remark = StringUtils.convertString(detail.getRemark());
            String checker = StringUtils.convertString(detail.getChecker());
            String startTime = StringUtils.convertString(detail.getStartTime());
            String endTime = StringUtils.convertString(detail.getEndTime());
            String storageDesc = StringUtils.convertString(detail.getStorageDesc());
            String nameNorms = StringUtils.convertString(detail.getNameNorms());
            String orgName = StringUtils.convertString(detail.getOrgName());
            String insertSql = "INSERT INTO main_material_inventory_detail (org_id,org_name, today, material_id, " +
                    "storage_id,name_norms, store_type, barrel_height, barrel_radius, barrel_cone, barrel_volume,\n" +
                    "enjoy_length, enjoy_width, enjoy_height, enjoy_volume, other_volume, sum_volume, ratio, weight, " +
                    "check_weight, is_check,\n" +
                    "checker, check_time, is_finance, finance, finance_time, status, remark, creator, create_time,\n" +
                    "updator, update_time,start_time,end_time,storage_desc)\n" +
                    "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
            Object[] objs = {detail.getOrgId(),orgName,detail.getToday(),detail.getMaterialId(),
                    detail.getStorageId(),nameNorms ,detail.getStoreType(),detail.getBarrelHeight(),
                    detail.getBarrelRadius(),detail.getBarrelCone(),detail.getBarrelVolume(),
                    detail.getEnjoyLength(),detail.getEnjoyWidth(),detail.getEnjoyHeight(),detail.getEnjoyVolume(),
                    detail.getOtherVolume(), detail.getSumVolume(),detail.getRatio(), detail.getWeight(),
                    detail.getCheckWeight(),0, checker,null,0,null, null, 0,
                    remark, creator,createTime_,"",createTime_,startTime,endTime,storageDesc};
            KeyHolder keyHolder = new GeneratedKeyHolder();
            JdbcTemplate jdbcTemplate = JDBCTemplateCache.getLocalJdbcTemplate(ds);
            jdbcTemplate.update(new PreparedStatementCreator() {
                @Override
                public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                    PreparedStatement ps = connection.prepareStatement(insertSql, new String[]{"ID"});
                    for (int i = 0; i < objs.length; i++) {
                        ps.setObject(i + 1, objs[i]);
                    }
                    return ps;
                }
            }, keyHolder);
            Long taskId = keyHolder.getKey().longValue();
            if (taskId < 1) {
                throw new MessageCenterException("新增本地结算数据错误");
            }
            String insertCloudSql = "INSERT INTO "+ds.getCode()+".main_material_inventory_detail (id,org_id,org_name, today, material_id, storage_id,\n" +
                    "name_norms, store_type, barrel_height, barrel_radius, barrel_cone, barrel_volume,\n" +
                    "enjoy_length, enjoy_width, enjoy_height, enjoy_volume, other_volume, sum_volume, ratio, weight, check_weight, is_check,\n" +
                    "checker, check_time, is_finance, finance, finance_time, status, remark, creator, create_time,\n" +
                    "updator, update_time,start_time,end_time,storage_desc)\n" +
                    "VALUES ("+ taskId +","+detail.getOrgId()+",'"+orgName+"', '"+detail.getToday()+"', "+detail.getMaterialId()
                    +", "+detail.getStorageId()+",'"+nameNorms+"', "+detail.getStoreType()+", "+detail.getBarrelHeight()+"," +
                    detail.getBarrelRadius()+", "+detail.getBarrelCone()+", "+detail.getBarrelVolume()+",\n" +
                    detail.getEnjoyLength()+", "+detail.getEnjoyWidth()+", "+detail.getEnjoyHeight()+", "+detail.getEnjoyVolume()+", " +
                    detail.getOtherVolume()+", "+detail.getSumVolume()+", "+detail.getRatio()+", "+detail.getWeight()+", " +
                    detail.getCheckWeight()+", 0,'"+checker+"', null, 0, '', null, 0, " +
                    "'" + remark+"', '"+creator+"', '"+createTime_+"','', '"+createTime_+"','"
                    +startTime+"','"+endTime +"','"+storageDesc+"') ON DUPLICATE KEY UPDATE org_id = VALUES(org_id), org_name = VALUES(org_name),\n" +
                    "today = VALUES(today),material_id = VALUES(material_id),storage_id = VALUES(storage_id),\n" +
                    "name_norms = VALUES(name_norms),store_type = VALUES(store_type)\n" +
                    ",barrel_height = VALUES(barrel_height),barrel_radius = VALUES(barrel_radius),\n" +
                    "barrel_cone = VALUES(barrel_cone),\n" +
                    "barrel_volume = VALUES(barrel_volume), enjoy_length = VALUES(enjoy_length),enjoy_width = VALUES(enjoy_width),\n" +
                    "enjoy_height = VALUES(enjoy_height),enjoy_volume = VALUES(enjoy_volume),other_volume = VALUES(other_volume),\n" +
                    "sum_volume = VALUES(sum_volume),ratio = VALUES(ratio),weight = VALUES(weight),\n" +
                    "check_weight = VALUES(check_weight),is_check = VALUES(is_check),updator = VALUES(updator),\n" +
                    "checker = VALUES(checker),is_finance = VALUES(is_finance),finance = VALUES(finance),\n" +
                    "status = VALUES(status),finance_time = VALUES(finance_time),check_time = VALUES(check_time),\n" +
                    "update_time = VALUES(update_time),start_time = VALUES(start_time),end_time = VALUES(end_time),\n" +
                    "storage_desc = VALUES(storage_desc)";
            Integer code = materialInventoryDetailDao.insertCloudSql(insertCloudSql);
            if (code > 0)
                return RestResultDto.success("新增成功");
        }
        throw new MessageCenterException("新增失败");
    }
    /**
     * 审核购进明细报表
     * @param orgId
     * @param today 时间点
     * @param creator
     * @param type 0 材料统计 1 财务
     * @return
     */
    public RestResultDto examineDetail(Long orgId, String today, String creator, Integer type) {
        if (StringUtils.isAllParamNull(orgId, today, type))
            throw new MessageCenterException("审核材料盘存明细表参数错误");

        DataSourceInfo ds = dsDao.queryDSByOriginIdV1(orgId,DataBaseEnum.MYSQL.getCode());
        if (ds == null || ds.getStatus() == 1 || ds.getType() != 0)
            throw new MessageCenterException("ERP数据源错误");
        Date nowDate = new Date();
        String nowTime = DateUtil.convertString(nowDate);
        String updateCloudSql = "update " + ds.getCode() + ".main_material_inventory_detail set updator = '" + creator
                + "',update_time='" + nowTime + "',checker = '" + creator + "' ";
        String updateSql = "update main_material_inventory_detail set updator = '" + creator
                + "',update_time='" + nowTime + "',checker = '" + creator + "' ";
        Integer code = -1;
        if (type == 0) {
            Integer total = materialInventoryDetailDao.findCheckTotal(ds.getCode(), orgId, today, 0, null);
            if (total < 1)
                throw new MessageCenterException("没有审核的数据");
            updateCloudSql += ",is_check = 1,check_time = '" + nowTime + "' " +
                    " where today = '" + today + "' and org_id = " + orgId;
            updateSql += ",is_check = 1,check_time = '" + nowTime + "' " +
                    " where today = '" + today + "' and org_id = " + orgId;
        } else if (type == 1) {
            Integer total = materialInventoryDetailDao.findCheckTotal(ds.getCode(), orgId, today, 0, null);
            if (total > 0)
                throw new MessageCenterException("材料统计未审核,请通知材料统计先行审核");
            total = materialInventoryDetailDao.findCheckTotal(ds.getCode(), orgId, today, 1, 0);
            if (total < 1)
                throw new MessageCenterException("没有未审核数据记录");

            updateCloudSql += "is_finance = 1,finance_time = '" + nowTime + "' " +
                    " where today = '" + today + "' and org_id = " + orgId;
            updateSql += "is_finance = 1,finance_time = '" + nowTime + "' " +
                    " where today = '" + today + "' and org_id = " + orgId;
        }
        code = materialInventoryDetailDao.updateCloudSql(updateCloudSql);
        if (code > 0) {
            JdbcTemplate jdbcTemplate = JDBCTemplateCache.getLocalJdbcTemplate(ds);
            code = jdbcTemplate.update(updateSql);
            if (code > 0)
                return RestResultDto.success("审核成功");
        }
        throw new MessageCenterException("审核类型错误");
    }
    /**
     * 更新盘存明细
     * @param detail
     * @return
     */
    public RestResultDto updateDetail(MainMaterialInventoryDetail detail) {
        if (detail == null || StringUtils.isNull(detail.getId()))
            throw new MessageCenterException("参数错误");
        DataSourceInfo ds = dsDao.queryDSByOriginIdV1(detail.getOrgId(),DataBaseEnum.MYSQL.getCode());
        if (ds == null || ds.getStatus() == 1 || ds.getType() != 0)
            throw new MessageCenterException("数据源参数错误");
        Date nowDate = new Date();
        detail.setUpdateTime(nowDate);
        MainMaterialInventoryDetail oldDetail = materialInventoryDetailDao.findCloudById(ds.getCode(), detail.getId());
        if (oldDetail == null || oldDetail.getStatus() == 1)
            throw new MessageCenterException("修改数据不存在或已被禁用");
        if (!StringUtils.isNull(oldDetail.getIsCheck()) && oldDetail.getIsCheck() == 1 )
            throw new MessageCenterException("数据已审核,不提供修改权限");
        if(!StringUtils.isNull(oldDetail.getIsFinance()) && oldDetail.getIsFinance() == 1)
            throw new MessageCenterException("数据已审核,不提供修改权限");
        if (StringUtils.isNull(detail.getIsCloud()) || detail.getIsCloud() == 1) {//本地数据直接新增
            Integer code = materialInventoryDetailDao.updateById(detail);
            if (code > 0)
                return RestResultDto.success("更新成功");
        } else {
            Long materialId = null;
            Long storageId = null;
            if (!StringUtils.isNull(detail.getMaterialId()) && !StringUtils.isNull(detail.getStorageId())
            && !detail.getMaterialId().equals(oldDetail.getMaterialId()) && !detail.getStorageId().equals(oldDetail.getStorageId())) {
                materialId = detail.getMaterialId();
                storageId = detail.getStorageId();
                MainMaterialInventoryDetail tempDetail = materialInventoryDetailDao.findOrgByStorage(ds.getCode(), detail.getOrgId(),
                        detail.getToday(), materialId, storageId);
                if (tempDetail != null)
                    throw new MessageCenterException(oldDetail.getToday() + "相同仓位、材料已存在盘存明细数据");
            }
            String updateSql = "";
            if (!StringUtils.isNull(detail.getMaterialId()))
                updateSql += " ,material_id = " + detail.getMaterialId();
            if (!StringUtils.isNull(detail.getStorageId()))
                updateSql += " ,storage_id = " + detail.getStorageId();
            if (!StringUtils.isNull(detail.getStoreType()))
                updateSql += " ,store_type = " + detail.getStoreType();
            if (!StringUtils.isNull(detail.getNameNorms()))
                updateSql += " ,name_norms = '" + detail.getNameNorms() + "'";
            if (!StringUtils.isNull(detail.getBarrelHeight()))
                updateSql += " ,barrel_height = " + detail.getBarrelHeight();
            if (!StringUtils.isNull(detail.getBarrelRadius()))
                updateSql += " ,barrel_radius = " + detail.getBarrelRadius();
            if (!StringUtils.isNull(detail.getBarrelCone()))
                updateSql += " ,barrel_cone = " + detail.getBarrelCone();
            if (!StringUtils.isNull(detail.getBarrelVolume()))
                updateSql += " ,barrel_volume = " + detail.getBarrelVolume();
            if (!StringUtils.isNull(detail.getEnjoyLength()))
                updateSql += " ,enjoy_length = " + detail.getEnjoyLength();
            if (!StringUtils.isNull(detail.getEnjoyWidth()))
                updateSql += " ,enjoy_width = " + detail.getEnjoyWidth();
            if (!StringUtils.isNull(detail.getEnjoyHeight()))
                updateSql += " ,enjoy_height = " + detail.getEnjoyHeight();
            if (!StringUtils.isNull(detail.getEnjoyVolume()))
                updateSql += " ,enjoy_volume = " + detail.getEnjoyVolume();
            if (!StringUtils.isNull(detail.getOtherVolume()))
                updateSql += " ,other_volume = " + detail.getOtherVolume();
            if (!StringUtils.isNull(detail.getSumVolume()))
                updateSql += " ,sum_volume = " + detail.getSumVolume();
            if (!StringUtils.isNull(detail.getRatio()))
                updateSql += " ,ratio = " + detail.getRatio();
            if (!StringUtils.isNull(detail.getWeight()))
                updateSql += " ,weight = " + detail.getWeight();
            if (!StringUtils.isNull(detail.getCheckWeight()))
                updateSql += " ,check_weight = " + detail.getCheckWeight();
            if (!StringUtils.isNull(detail.getNameNorms()))
                updateSql += " ,name_norms = '" + detail.getNameNorms() + "'";
            if (!StringUtils.isNull(detail.getRemark()))
                updateSql += " ,remark = '" + detail.getRemark() + "'";
            if (!StringUtils.isNull(detail.getStorageDesc()))
                updateSql += " ,storage_desc = '" + detail.getStorageDesc() + "'";
            String updateCloudSql = "update " + ds.getCode() + ".main_material_inventory_detail set updator = '" + detail.getUpdator()
                    + "', update_time = '" + DateUtil.convertString(nowDate) + "' " + updateSql;
            updateSql = "update main_material_inventory_detail set updator = '" + detail.getUpdator()
                    + "', update_time = '" + DateUtil.convertString(nowDate) + "' " + updateSql;
            updateCloudSql += " where id = " + detail.getId() + " and org_id = " + detail.getOrgId();
            updateSql += " where id = " + detail.getId() + " and org_id = " + detail.getOrgId();
            Integer code = materialInventoryDetailDao.updateCloudSql(updateCloudSql);
            if (code > 0) {
                JdbcTemplate jdbcTemplate = JDBCTemplateCache.getLocalJdbcTemplate(ds);
                code = jdbcTemplate.update(updateSql);
                return RestResultDto.success("更新成功");
            }
        }
        throw new MessageCenterException("更新失败");
    }

    /**
     * 更新明细状态
     * @param id
     * @param status
     * @param creator
     * @return
     */
    public RestResultDto updateStatus(Long id, Long orgId, Integer status, String creator) {
        if (StringUtils.isAllParamNull(id, orgId, status))
            throw new MessageCenterException("参数错误");
        DataSourceInfo ds = dsDao.queryDSByOriginIdV1(orgId,DataBaseEnum.MYSQL.getCode());
        if (ds == null || ds.getStatus() == 1 || ds.getType() != 0)
            throw new MessageCenterException("数据源参数错误");
        Date nowDate = new Date();
        MainMaterialInventoryDetail oldDetail = materialInventoryDetailDao.findCloudById(ds.getCode(), id);
        if (oldDetail == null)
            throw new MessageCenterException("修改数据不存在");
        if ((!StringUtils.isNull(oldDetail.getIsCheck()) && oldDetail.getIsCheck() == 1 )
                && (!StringUtils.isNull(oldDetail.getIsFinance()) && oldDetail.getIsFinance() == 1))
            throw new MessageCenterException("数据已审核,不提供修改权限");
        String updateCloudSql = "update " + ds.getCode() + ".main_material_inventory_detail set updator = '" + creator
                + "', update_time = '" + DateUtil.convertString(nowDate) + "',status = " + status;
        String updateSql = "update main_material_inventory_detail set updator = '" + creator
                + "', update_time = '" + DateUtil.convertString(nowDate) + "',status = " + status;
        updateCloudSql += " where id = " + id + " and org_id = " + orgId;
        updateSql += " where id = " + id + " and org_id = " + orgId;
        Integer code = materialInventoryDetailDao.updateCloudSql(updateCloudSql);
        if (code > 0) {
            JdbcTemplate jdbcTemplate = JDBCTemplateCache.getLocalJdbcTemplate(ds);
            code = jdbcTemplate.update(updateSql);
            if (code > 0)
                return RestResultDto.success("更新成功");
        }
        throw new MessageCenterException("更新失败");
    }
    /**
     * 查询是否已审核
     * @param orgId
     * @param today
     * @return
     */
    public Integer findCheck(String dbCode, Long orgId, String today) {
        if (StringUtils.isAllParamNull(orgId, today))
            throw new MessageCenterException("查询审核信息参数错误");
        Integer total = materialInventoryDetailDao.findCheckTotal(dbCode, orgId, today, 1, null);
        if (total > 0)
            return total;
        total = materialInventoryDetailDao.findCheckTotal(dbCode, orgId, today, null, 1);
        if (total > 0)
            return total;
        return 0;
    }
    /**
     * 补收及任务计算
     * @param orgId
     * @param today
     * @param storageId
     * @param creator
     * @param isCloud
     * @return
     */
    public RestResultDto syncDetail(Long orgId, String today, String startTime, String endTime, Long storageId, String creator, Integer isCloud) {
        if (StringUtils.isAllParamNull(orgId, today, isCloud))
            throw new MessageCenterException("参数错误");

        DataSourceInfo ds = dsDao.queryDSByOriginIdV1(orgId,DataBaseEnum.MYSQL.getCode());
        if (ds == null || ds.getStatus() == 1 || ds.getType() != 0)
            throw new MessageCenterException("数据源参数错误");
        Integer checkTotal = materialInventoryDetailDao.findCheckTotal(ds.getCode(), orgId, today, 1, null);
        if (checkTotal > 0)
            throw new MessageCenterException(today + "盘存明细表已存在审核数据");
        checkTotal = materialInventoryDetailDao.findCheckTotal(ds.getCode(), orgId, today, null, 1);
        if (checkTotal > 0)
            throw new MessageCenterException(today + "盘存明细表已存在审核数据");

        SysStorageVo storageVo = new SysStorageVo();
        storageVo.setOrgId(orgId);
        if (!StringUtils.isNull(storageId))
            storageVo.setStorageId(storageId);
        storageVo.setIsInventory(0);//参与盘存的数据
        List<SysStorageVo> storageVoList = storageDao.cloudPage(ds.getCode(), storageVo);
        if (storageVoList == null || storageVoList.size() == 0)
            throw new MessageCenterException("未获取到同步数据");

        Date nowDate = new Date();
        String orgName = ds.getName();
        List<MainMaterialInventoryDetail> detailList = new ArrayList<>();
        List<Object[]> insertList = new ArrayList();
        String nowTime = DateUtil.convertString(nowDate);
        for (int i = 0; i < storageVoList.size(); i++) {
            SysStorageVo storage = storageVoList.get(i);
            Long storageId_ = storage.getId();
            Long materialId = storage.getMaterialId();
            String nameNorms = storage.getNameNorms();
            SysStorageLog storageLog = storageLogDao.findTakeTimeOrErpStorageV1(ds.getCode(), storage.getLineId(), storageId_,
                    null, 0, endTime);
            if (storageLog != null) {
                materialId = storageLog.getMaterialId();
                nameNorms = storageLog.getMaterial();
            }
            MainMaterialInventoryDetail oldDetail = materialInventoryDetailDao.findOrgByStorage(ds.getCode(), orgId,
                    today, materialId, storageId_);
            if (oldDetail != null) {
                oldDetail.setNameNorms(nameNorms);
                oldDetail.setMaterialId(materialId);
                continue;
            }
            MainMaterialInventoryDetail detail = new MainMaterialInventoryDetail(orgId, orgName, today, materialId,
                    storageId_, nameNorms, storage.getType(), 0.0, 0.0, 0.0, 0.0,
                    0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
                    storage.getCoefficient(), 0.0, 0.0, storage.getStorageDesc(), startTime, endTime,
                    0, 0);
            detail.setRatio(storage.getCoefficient());
            detail.setBarrelRadius(storage.getRadius());
            detail.setStatus(0);
            detail.setCreator(creator);
            detail.setCreateTime(nowDate);
            detailList.add(detail);
            if (isCloud == 0) {
                Object[] objs = {orgId, orgName, today, materialId,
                        storageId_, storage.getNameNorms(), storage.getType(), 0.0, 0.0, 0.0, 0.0,
                        0.0, 0.0, 0.0, 0.0, 0.0, 0.0, storage.getCoefficient(), 0.0, 0.0, storage.getStorageDesc(), startTime, endTime,
                        0, 0,0,creator,nowTime};
                insertList.add(objs);
            }
        }
        if (detailList == null || detailList.size() == 0)
            throw new MessageCenterException("没有新增同步数据");
        Integer code = materialInventoryDetailDao.saveCloudBatch(ds.getCode(), detailList);
        if (code < 1)
            throw new MessageCenterException("同步新增数据异常");

        if (isCloud == 0) {
            if (insertList == null || insertList.size() == 0)
                throw new MessageCenterException("没有新增同步数据");
            String insertSql = "INSERT INTO main_material_inventory_detail (org_id,org_name, today, material_id, storage_id,\n" +
                    "name_norms, store_type, barrel_height, barrel_radius, barrel_cone, barrel_volume,enjoy_length, enjoy_width, enjoy_height, enjoy_volume, " +
                    "other_volume, sum_volume, ratio, weight, check_weight, \n" +
                    "storage_desc,start_time,end_time,is_check, is_finance, status, creator, create_time) " +
                    " values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
            JdbcTemplate jdbcTemplate = JDBCTemplateCache.getLocalJdbcTemplate(ds);
            jdbcTemplate.batchUpdate(insertSql, insertList);
            return RestResultDto.success("同步新增成功");
        }
        return RestResultDto.success("同步新增成功");
    }
}